package es.palma.controlSemanal.comunicaciones;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.graphics.drawable.Drawable;
import es.palma.controlSemanal.entities.Pesada;

public class Comunicador {
	private static final String urlInsert = "http://controlsemanal.appspot.com/insertPeso";
	private static final String urlResults = "http://controlsemanal.appspot.com/";
	private static final String urlChart = "http://controlsemanal.appspot.com/chartGenerator";
	
	public static List<Pesada> getPesadas() {
		List<Pesada> salida = new ArrayList<Pesada>();
		
		URL url;
		try {
			url = new URL(urlResults);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setDoOutput(true);
			http.setDoInput(true);
			
			BufferedReader in= new BufferedReader(new InputStreamReader(http.getInputStream()));
			String linea = in.readLine();
			in.close();
			JSONArray json = new JSONArray(linea);
			for(int i=0; i<json.length(); i++) {
				JSONObject jsonObject = json.getJSONObject(i);
				Pesada pesada = new Pesada();
				pesada.setCintura(Float.valueOf(jsonObject.getString("cintura")));
				pesada.setFecha(jsonObject.getString("fecha"));
				pesada.setPeso(Float.valueOf(jsonObject.getString("peso")));
				salida.add(pesada);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return salida;
	}
	
	public static Drawable getChartPeso(List<Pesada> pesadas) throws IOException {
		
		URL url = new URL(urlChart);
		HttpURLConnection http = (HttpURLConnection) url.openConnection();
		http.setDoOutput(true);
		http.setDoInput(true);
		OutputStream outHttp=http.getOutputStream();
		PrintWriter pw=new PrintWriter(outHttp);
		pw.print("tipo=peso");
		pw.flush();
		pw.close();
		BufferedReader in= new BufferedReader(new InputStreamReader(http.getInputStream()));
		String direccion = in.readLine();
		in.close();
		
		url = new URL(direccion);
		http = (HttpURLConnection) url.openConnection();
		http.setDoOutput(true);
		http.setDoInput(true);
			
		Drawable salida = Drawable.createFromStream(http.getInputStream(), "grafico");
		
		return salida;
	}
}
